cd ${work}3_lgkp\code

cap log close
clear *
set more off

*cap do "${code}/housekeeping.do"
cap do housekeeping.do
*cap log using "${code}/log.log",replace

local startloop = 1

*Section 1: Code to generate tables and figures
cap {
qui {
*	!rm -rf ${tables}
*	cap mkdir ${tables}

	global dirnum = 0
	global worklocal = "${work}/${dirnum}"
	!rm -rf "${worklocal}/"
	cap mkdir "${worklocal}"

	cd ${rootfile}
		!cp -r * "${worklocal}"

	cd "${worklocal}"
	noi dis "> ${dirnum}"
	qui do ${code}/01_sample.do
	qui do ${code}/02_pf.do
	qui do ${code}/03_getrhos.do	
*	qui do ${code}/05_CDfirm.do
	cd ${worklocal}
	!rm -rf dump/
	!rm -rf rhos/
*	local llist = "rootfile.dta qpred.dta CDdata_&_theta.dta AltCD_theta.dta rootfile_temp.dta tlogcoefpost.dta locationdata.dta omega_spfs.dta singleproduct_data.dta data_&_theta.dta rhos.dta"
	local llist = "data_&_theta.dta rootfile.dta rootfile_temp.dta singleproduct_data.dta"
	foreach i of local llist {
		cap erase `i'
		}
		
}
}

/*
*Section 2: Code to generate standard errors for Tables 7,9,10
local endloop = 500
qui forval iter=`startloop'/`endloop' {
	global dirnum = `iter'
	set seed ${dirnum}
	noi dis "> ${dirnum}"
	global worklocal = "${work}/${dirnum}"
	!rm -rf "${worklocal}/"
	cap mkdir "${worklocal}"
	cd ${rootfile}
		!cp -r * "${worklocal}"
	cd "${worklocal}"

	clear
	use rootfile,clear
	keep fid cl_nic
	duplicates drop
		isid fid
	*draw bootstrap sample for the entire firm...
	bsample
	keep fid
	
	g fidb = 10000+_n
	sort fid
	saveold tmp_bsample${dirnum},replace

	*merge in bootstrap ID's (note: there will be duplicates fup12-year (firm-product-unit-year obs)
		use rootfile,clear
		sort fid
		joinby fid using tmp_bsample${dirnum}
			rename fid fid_original
			rename fidb fid
			foreach i of numlist 2 4 6 8 12 {
				egen fup`i'_tmp = group(fid up`i')
				rename fup`i' fup`i'_original
				rename fup`i'_tmp fup`i'
				}
		save rootfile,replace
	do ${code}/01_sample.do
	do ${code}/02_pf.do 
	do ${code}/03_getrhos.do
	do ${code}/06_output_bootstrap.do

	cd ${worklocal}
        !rm -rf dump/
        !rm -rf rhos/
		
	local llist = "rootfile.dta qpred.dta CDdata_&_theta.dta AltCD_theta.dta rootfile_temp.dta tlogcoefpost.dta locationdata.dta omega_spfs.dta singleproduct_data.dta data_&_theta.dta rhos.dta"
	foreach i of local llist {
		cap erase `i'
		}
}


*go back to main folder (work/0)
cd  "${work}/0"

*generate bootstrap standard errors for Tables 7,9,10
do ${code}/07_bootstrap-standarderrors.do

*creates tables
qui do ${code}/08_output.do

noi dis ["__Finished!__"]
qui log close
